package com.newsappserver.newsservice.provider.online.service;

import com.newsappserver.newsservice.defines.ApiResponse;
import com.newsappserver.newsservice.provider.online.data.dto.response.FreeApiNewsResponse;
import com.newsappserver.newsservice.provider.online.data.dto.response.FreeApiResponse;
import com.newsappserver.newsservice.provider.online.data.entity.FreeApiNews;
import com.newsappserver.newsservice.provider.online.repository.FreeApiNewsRepo;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
public class FreeApiNewsService {
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    private FreeApiNewsRepo freeApiNewsRepo;

    // 根据类型获得在线新闻
    public FreeApiResponse getNewsByType(String type) {
        log.debug("getNewsByType: {}", type);
        log.debug("restTemplate: {}", restTemplate);

        String url = "http://v.juhe.cn/toutiao/index?"
                + "key=d268884b9b07c0eb9d6093dc54116018" // 参数key
                + "&type=" + type; // 参数type
        log.debug("Api Watch: getNewsByType: {}", url);
        return restTemplate.getForObject(url, FreeApiResponse.class);
    }

    //
    public void fetchAndSaveNews() {
        String url = "http://v.juhe.cn/toutiao/index?"
                + "key=d268884b9b07c0eb9d6093dc54116018" // 参数key
                + "&type=" + "top"; // 参数type

        FreeApiResponse response = restTemplate.getForObject(url, FreeApiResponse.class);
        if (response != null && response.getResult() != null) {
            List<FreeApiNewsResponse> newsList = response.getResult().getData();
            for (FreeApiNewsResponse newsDTO : newsList) {
                FreeApiNews newsEntity = new FreeApiNews();
                newsEntity.setTitle(newsDTO.getTitle());
                newsEntity.setUniquekey(newsDTO.getUniquekey());
                newsEntity.setUrl(newsDTO.getUrl());
                newsEntity.setCategory(newsDTO.getCategory());
                newsEntity.setDate(LocalDateTime.parse(newsDTO.getDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                freeApiNewsRepo.save(newsEntity);
            }
        }
    }

}
